"use strict";
const WebSocket = require('ws');
const utils = require("./utils.js");

const max_num = 1; //客户端数量
const send_num = 4; //每个客户端发送消息的数量
const send_interval = 1; //发送消息的间隔

let openCount = 0; //连接数
let openingCount = 0; //正在连接数量
let receivedCount = 0;
let msgCount = 0;

let clients = [];
for (let i = 0; i < max_num; i++) {
    let ws = new WebSocket('ws://majiang-server:8888');
    clients.push(ws);
    ws.on('open', function open() {
        openCount++;
        openingCount++;
        let i = 0;
        let timer = setInterval(() => {
            i++;
            if (i <= send_num) {
                ws.send(JSON.stringify({
                    timestamp: new Date().getTime(),
                    nonce: utils.randomString(20),
                    session: "1",
                    method: "createRoom"
                }), () => {
                    msgCount++;
                });
            } else {
                clearInterval(timer);
                let start = new Date();
                let timer2 = setInterval(() => {
                    if (receivedCount == max_num * send_num) {
                        clearInterval(timer2);
                        logAll();
                        let time = new Date().getTime() - start.getTime();
                        console.log("总共耗时：" + time + "ms");
                        console.log("qps：" + (max_num * send_num / time * 1000));
                        for (let client of clients) {
                            process.stdout.write(".");
                            client.close();
                        }
                        console.log("");
                    }
                }, 100);
            }
        }, send_interval);

    });

    ws.on('message', function(data, flags) {
        console.log(data);
        receivedCount++;
        logAll();
    });

    ws.on('close', function() {
        openingCount--;
    });

    ws.on('error', function(err) {
        console.log(err);
    });
}

function logAll() {
    console.log("正在连接数量：" + openingCount);
    console.log("掉线率：" + (1 - openingCount / max_num));
    console.log("收到消息数量：" + receivedCount);
    console.log("收到消息成功率：" + receivedCount / max_num / send_num);
}
